<template>
    <v-container style="width:100%;">
        <v-row justify="space-between" class="pt-1">
            <v-subheader class="grey--text text--darken-3" style="font-size: 20px">
                {{ title }}
            </v-subheader>
            <div>
                <v-btn
                    v-if="importCsvButton"
                    outlined
                    class="mr-4"
                    @click="$emit('import-dialog')"
                >
                    Import CSV
                </v-btn>
                <!-- <v-btn
                    v-if="selectedItems.length > 0"
                    outlined
                    class="mr-4"
                    @click="$emit('export-pdf')"
                >
                    Export to PDF
                </v-btn>
                <v-btn
                    v-if="selectedItems.length > 0"
                    outlined
                    class="mr-4"
                    @click="$emit('export-excel')"
                >
                    Export to Excel
                </v-btn> -->
                <v-btn
                    v-if="!hideAddNew"
                    v-can:create="featureName"
                    color="primary"
                    class="mr-4"
                    @click="$emit('create')"
                >
                    Add New
                </v-btn>
            </div>
        </v-row>
        <v-divider></v-divider>

        <v-row justify="space-between" style="margin-bottom: -20px; margin-top: 5px">
            <v-col cols="12" sm="6" md="4">
                <v-text-field
                    v-model="paginateConfig.searchText"
                    label="Search"
                    solo
                    dense
                    append-icon="mdi-magnify"
                    @click:append="fetch"
                    @keyup.enter.native="fetch"
                />
            </v-col>
            <v-col cols="12" sm="4" md="4">
                <v-radio-group
                    v-model="paginateConfig.filter"
                    row
                    style="margin-top: 5px;"
                >
                    <v-radio
                        v-for="(filter, index) in filters"
                        :key="index"
                        :label="filter.label"
                        :value="filter.value"
                    ></v-radio>
                </v-radio-group>
            </v-col>
            <v-col cols="12" sm="2" md="2">
                <v-select
                    :items="[
                        25, 50, 100, 200,
                    ]"
                    v-model="paginateConfig.perPage"
                    @input="fetch"
                    label="Outlined style"
                    solo
                    dense
                ></v-select>
            </v-col>
        </v-row>

        <v-card class="mx-auto">
            <v-layout column style="height: 60vh">
                <v-flex style="overflow: auto;">
                    <v-data-table
                        height="60vh"
                        v-model="selectedItems"
                        :items-per-page="paginateConfig.perPage"
                        :show-select="false"
                        :single-select="false"
                        :page.sync="paginateConfig.page"
                        item-key="id"
                        :headers="headersWithAction"
                        :items="items"
                        fixed-header
                        hide-default-footer
                        :class="hasEditPermission ? 'row-pointer' : ''"
                        @click:row="hasEditPermission ? $emit('update', $event) : showNoEditPermissionDialog()"
                    >
                        <template v-slot:item.custom="" />
                        <template v-slot:item.actions="{ item }">
                            <!-- <v-icon color="blue" v-can:update="featureName" @click="$emit('update', item)" class="mr-2">mdi-square-edit-outline</v-icon> -->
                            <v-icon color="red" v-can:delete="featureName" @click.stop="$emit('delete', item)">mdi-trash-can-outline</v-icon>
                        </template>
                        <!-- Expose inner slot for usage -->
                        <template v-for="(_, slot) of $scopedSlots" v-slot:[slot]="scope"><slot :name="slot" v-bind="scope"/></template>
                    </v-data-table>
                </v-flex>
            </v-layout>
        </v-card>

        <v-pagination
            class="mt-5"
            v-model="paginateConfig.page"
            :length="paginateConfig.total"
            :page="paginateConfig.page"
            :total-visible="paginateConfig.total"
            @input="fetch"
        >
        </v-pagination>
    </v-container>
</template>

<script lang="ts">
import Vue from 'vue';
import { PaginateConfig, PaginateResult } from '@/type/Shared';
import store from '@/store/Index';
import { listenEvent } from '@/misc/EventBus';

export default Vue.extend({
    name: 'DataTable',
    props: {
        title: {
            type: String,
            default: 'Title',
        },
        headers: {
            type: Array,
            required: true,
        },
        fetchMethod: {
            type: Function,
            required: true,
        },
        importCsvButton: {
            type: Boolean,
            default: false,
        },
        hideAddNew: {
            type: Boolean,
            default: false,
        },
        featureName: {
            type: String,
            required: true,
        },
        filters: {
            type: Array,
        },
    },
    computed: {
        headersWithAction(): any[] {
            return (this.headers as Array<any>).concat([
                { text: 'Actions', value: 'actions' },
            ]);
        },
        hasEditPermission(): boolean {
            return store.auth.hasPermission(this.featureName, 'update');
        },
    },
    data(): {
        items: any[];
        selectedItems: any[];
        paginateConfig: PaginateConfig;
        } {
        return {
            items: [],
            selectedItems: [],
            paginateConfig: {
                perPage: 25,
                total: 0,
                page: 1,
                searchText: '',
                column: 'id',
                direction: 'desc',
                filter: '',
            },
        };
    },
    watch: {
        'paginateConfig.filter': {
            handler() {
                this.fetch();
            },
            deep: true,
        },
    },
    async mounted() {
        await this.fetch();

        listenEvent('update-data-table', async () => {
            await this.fetch();
        });
    },
    methods: {
        async fetch() {
            await store.loader.run(async () => {
                const paginatedResult = await this.fetchMethod(this.paginateConfig) as PaginateResult<any>;
                this.paginateConfig.page = paginatedResult.current_page;
                this.paginateConfig.total = paginatedResult.last_page;

                if (this.paginateConfig.page > this.paginateConfig.total) {
                    this.paginateConfig.page = 1;
                }

                this.items = paginatedResult.data;
            });
        },
        showNoEditPermissionDialog() {
            store.alert.show('You do not have permission to edit', 'warning');
        },
    },
});
</script>

<style lang="css" scoped>
.row-pointer >>> tbody tr :hover {
    cursor: pointer;
}
</style>
